package com.dlc.shop.jky.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linchuang.seneca.jky.bizdata.vend.goodssourcecreate.GoodsSourceCreate;
import com.linchuang.seneca.jky.bizdata.vend.goodssourcecreate.core.GoodsSourceCreateRequestBizData;
import com.linchuang.seneca.jky.bizdata.vend.goodssourcegetbycol.GoodsSourceBycolRequestBizData;
import com.linchuang.seneca.jky.bizdata.vend.goodssourcegetbycol.GoodsSourceBycolResponseBizData;
import com.linchuang.seneca.jky.bizdata.vend.vendcreate.VendLinkmanList;
import com.linchuang.seneca.jky.bizdata.vend.vendcreate.VendPayAccountList;
import com.linchuang.seneca.jky.bizdata.vend.vendcreate.core.VendCreateRequestBizData;
import com.linchuang.seneca.jky.bizdata.vend.vendcreate.core.VendCreateResponseBizData;
import com.linchuang.seneca.jky.exception.JkyException;
import com.linchuang.seneca.jky.response.JackyunResponse;
import com.dlc.shop.allinpay.service.AllinpayCompanyService;
import com.dlc.shop.bean.dto.ShopAuditingInfoDto;
import com.dlc.shop.bean.enums.AuditStatus;
import com.dlc.shop.bean.enums.PositionType;
import com.dlc.shop.bean.model.ShopBankCard;
import com.dlc.shop.bean.model.ShopDetail;
import com.dlc.shop.bean.model.Sku;
import com.dlc.shop.bean.param.AuditingInfoParam;
import com.dlc.shop.bean.param.EsProductParam;
import com.dlc.shop.bean.vo.ShopCompanyVO;
import com.dlc.shop.bean.vo.search.ProductSearchVO;
import com.dlc.shop.common.allinpay.constant.IdCardCollectProcessStatus;
import com.dlc.shop.common.jky.JkyMp;
import com.dlc.shop.common.util.EsPageVO;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.jky.common.service.ErpVendCreateV2Service;
import com.dlc.shop.jky.common.service.JackyunOpenClientService;
import com.dlc.shop.search.common.constant.EsConstant;
import com.dlc.shop.search.common.param.EsPageParam;
import com.dlc.shop.search.common.service.SearchProductService;
import com.dlc.shop.service.*;
import com.dlc.shop.sys.common.model.ShopEmployee;
import com.dlc.shop.sys.common.service.ShopEmployeeService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.dlc.shop.common.util.DateUtils.getDisDay;


@Service
@AllArgsConstructor
public class ErpVendCreateV2ServiceImpl implements ErpVendCreateV2Service {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final JackyunOpenClientService jackyunOpenClientService;
    private final ShopConfig shopConfig;
    private final ShopAuditingService shopAuditingService;
    private final ShopDetailService shopDetailService;
    private final ShopEmployeeService shopEmployeeService;
    private final ShopBankCardService shopBankCardService;
    private final ShopCompanyService shopCompanyService;
    private final AllinpayCompanyService allinpayCompanyService;
    private final SkuService skuService;
    private final SearchProductService searchProductService;

    @Override
    public List<VendCreateResponseBizData> erpVendCreateV2(VendCreateRequestBizData bizData, Long shopId) throws JkyException {

        List<VendCreateResponseBizData> list = new ArrayList();
        Page<ShopAuditingInfoDto> page = new Page<>();
        page.setSize(1000);
        page.setCurrent(1);
        AuditingInfoParam auditingInfoParam = new AuditingInfoParam();
        auditingInfoParam.setShopStatusList(Arrays.asList(0, 1, 2, 3));
        IPage<ShopAuditingInfoDto> shopAuditingInfoDtoIPage = shopAuditingService.auditingInfoList(page, auditingInfoParam);
        for (ShopAuditingInfoDto shopAuditingInfoDto : shopAuditingInfoDtoIPage.getRecords()) {
            VendCreateResponseBizData orderRequest = new VendCreateResponseBizData();
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopAuditingInfoDto.getShopId());
            shopId = shopDetail.getShopId();
            bizData.setCode(shopDetail.getShopId() + "");
            bizData.setName(shopDetail.getShopName());
            bizData.setClassId(shopDetail.getIsSupplier());
            if (shopDetail.getIsSupplier() != null && shopDetail.getIsSupplier() == 0) {
                bizData.setClassName("第三方店铺");
            } else {
                if (shopDetail.getIsSupplier() != null && shopDetail.getIsSupplier() == 1)
                    bizData.setClassName("平台自谈供应商");
            }
            if (shopDetail.getIsSupplier() == null)
                bizData.setClassName("平台自谈供应商");
            bizData.setLeader(shopDetail.getUserName());
            bizData.setTel(shopDetail.getTel());
            bizData.setMemo(shopDetail.getIntro());
            //员工写入
            List<ShopEmployee> shopEmployeeList = shopEmployeeService.listEnableEmployee(shopId);
            List<VendLinkmanList> vendLinkmanList = new ArrayList<>();
            for (ShopEmployee shopEmployee : shopEmployeeList) {
                VendLinkmanList vendLinkman = new VendLinkmanList();
                vendLinkman.setLinkman(shopEmployee.getUsername());
                vendLinkman.setLinktel(shopEmployee.getMobile());
                vendLinkman.setEmail(shopEmployee.getEmail());
                vendLinkman.setPosition((Objects.equals(PositionType.ADMIN.value(), shopEmployee.getType()) ? "店铺管理员" : "员工"));
                vendLinkmanList.add(vendLinkman);
            }
            bizData.setVendLinkmanList(vendLinkmanList);
            List<VendPayAccountList> vendPayAccountList = new ArrayList<>();
            List<ShopBankCard> shopBankCards = shopBankCardService.list(new LambdaQueryWrapper<ShopBankCard>().eq(ShopBankCard::getShopId, shopId).eq(ShopBankCard::getStatus, 1));
            Integer status = 1;
            if (allinpayCompanyService.getIsAllinpay()) {
                // 影印件还没通过审核
                if (!Objects.equals(shopDetail.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                    status = AuditStatus.WAITAUDIT.value();
                }
            }
            ShopCompanyVO shopCompany = shopCompanyService.getShopCompanyByShopIdAndStatus(shopId, status);
            for (ShopBankCard shopBankCard : shopBankCards) {
                VendPayAccountList vendPayAccount = new VendPayAccountList();
                vendPayAccount.setCompanyId(shopId);
                vendPayAccount.setCompanyName(shopCompany.getFirmName());
                vendPayAccount.setAccountTypeCode("BANK");
                vendPayAccount.setAccountTypeName(shopBankCard.getBankName());
                vendPayAccount.setBankacct(shopBankCard.getOpeningBank());
                vendPayAccount.setBankacct(shopBankCard.getBankCardNo());
                vendPayAccount.setAccName(shopBankCard.getRecipientName());
                vendPayAccount.setIsDefault(shopBankCard.getIsDefault() + "");
                vendPayAccountList.add(vendPayAccount);
            }
            bizData.setVendPayAccountList(vendPayAccountList);
            JkyMp jky = shopConfig.getJky();
            bizData.setMethod("erp.vend.create.v2");

            JackyunResponse call = jackyunOpenClientService.call(jky, bizData);
            logger.info("供应商新增编辑，返回数据：=====》"+call.toString());
            if ("0".equals(call.getCode())) {
                orderRequest.setCode("0");
                orderRequest.setMsg(call.getMsg());
                orderRequest.setSubmessage(bizData.getName());
                list.add(orderRequest);
                // throw new JkyException("0", call.getMsg() + bizData.getName());
            } else {
                JSONObject data = JSONObject.parseObject(call.getResult().toString());
                String data1 = data.get("data").toString();
                //转化为需要的数据
                orderRequest = JSONObject.parseObject(data1).toJavaObject(VendCreateResponseBizData.class);
                logger.info(orderRequest.getVendId());
                list.add(orderRequest);
            }
        }

        return list;
    }

    @Override
    public void GoodsSourceCreate(Integer pageIndex, Integer pageSize) throws JkyException {

        PageParam<Sku> page = new PageParam<>();
        page.setCurrent(pageIndex);
        page.setSize(pageSize);
        IPage<Sku> skuIPage = skuService.pageGoodsSourceStatusSku(page, null);
        for (Sku sku : skuIPage.getRecords()) {

            logger.info("接收到sku 的信息为 ："+sku.toString());
            if (sku.getShopId() == 0){
                continue;
            }
            List<GoodsSourceCreate> list = new ArrayList<>();
            Long skuId = sku.getSkuId();
            GoodsSourceCreate goodsSourceCreate = new GoodsSourceCreate();
            goodsSourceCreate.setSkuBarcode(sku.getPartyCode());
            goodsSourceCreate.setMemo(sku.getSkuId() + "-" + sku.getPartyCode() + sku.getProdId() + "-" + sku.getShopId() + "");
            goodsSourceCreate.setCurrencyCode("CNY");
            goodsSourceCreate.setCurrencyName("人民币");
            if (sku.getSupplierPrice() == null){
                continue;
            }
            goodsSourceCreate.setPrice(BigDecimal.valueOf(sku.getSupplierPrice()).setScale(8, RoundingMode.HALF_UP));
            goodsSourceCreate.setVendorGoodsNo(sku.getProdId() + "-" + sku.getShopId());
            goodsSourceCreate.setVendorNo(sku.getShopId() + "");
            logger.info("报价信息 ：店铺id "+sku.getShopId());
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(sku.getShopId());
            goodsSourceCreate.setUnitName(shopDetail.getShopName());
            byte isDefault = 0;
            goodsSourceCreate.setIsDefault(isDefault);
            JkyMp jky = shopConfig.getJky();

            list.add(goodsSourceCreate);
            JackyunResponse call = jackyunOpenClientService.call("erp.goodssource.create", jky, list);
            logger.info("报价完成后返回信息：" + call.getResult().toString());
            if ("0".equals(call.getCode())) {
                //throw new JkyException("0", call.getMsg() + goodsSourceCreates.toString());
                logger.info("报价完成后返回信息：" + call.getMsg());
                if (call.getMsg().contains("条码不存在:") && getDisDay(sku.getUpdateTime(),new Date()) > 3){
                    //条码不存在 并且大于三天
                    skuService.updateGoodSourceStatus(2, skuId);
                }
                if(call.getMsg().equals("同一个供应商下不能创建相同规格和单位的供应商报价！")){
                    //成功了。更新状态
                    skuService.updateGoodSourceStatus(1, skuId);
                }
            } else {
                //成功了。更新状态
                skuService.updateGoodSourceStatus(1, skuId);
            }
        }

         if (skuIPage.getPages() > pageIndex) {
             GoodsSourceCreate(pageIndex + 1, pageSize);
         }
    }

}
